$(function(){

   // $('.wContent').hide();

   
   $('input').keyup(function(){
       $(this).parent().find('.errorMsg').hide();

   });
 $('.buttonCross').live('click',function(){
         $(this).parent().remove();
     });   
});
          
 function saveProfile()
 {
                                                                                                     
    var name = $.trim($('#uName').val());
    var email = $.trim($('#uEmail').val());    
    var mobile =$.trim($('#uMobilePhone').val());
    var ulang= $('#uLang').prop("selectedIndex");
    var uDept= $('#uDept').prop("selectedIndex");
    var isError =false;    

    if (name=="")
    {
         showError($('#uName').parent().find('.errorMsg'));        
         isError  =true;;
    }
    
    if (email.match(/^([\w]+)(.[\w]+)*@([\w]+)(.[\w]{2,3}){1,2}$/)==null)
    {
        showError($('#uEmail').parent().find('.errorMsg'));        
         isError  =true;;
    }
    if (mobile!= "" && mobile.match(/^6?01\d{8,9}$/)==null)    
    {
        showError($('#uMobilePhone').parent().find('.errorMsg'));
         isError  =true;;
    }
    
    console.log('mobile'+mobile+',email:'+email+',lang:'+ulang+',dept:'+uDept);
          
    if (isError) return ;
    ulang++;
    uDept++;
    var url =  window.location.href + '/ajaxSaveProfile';    
    $.post(url ,{name:name,email:email,mobile:mobile,lang:ulang,dept:uDept},
        function(data){                         
            showError($('#saveProfile .errorMsg'),'    ' + data.status,5000);            
          },"json");    
 };         
                                                     
                                                     
                                                     
function showError(ele, msg,fadeout)
{
    if(typeof msg!= 'undefined') ele.text(msg);
    ele.fadeIn("fast");
    if (typeof fadeout != 'undefined')
    { 
        setTimeout(function(){
            ele.fadeOut(fadeout);
        },2000)
    }    
} 
 function changePsw()
{
    var oldpsw = $.trim($('#password_old').val());
    var newpsw = $.trim($('#password_new').val());
    var newpsw2 = $.trim($('#password_confirm').val());
    if (oldpsw =="" )
    {
        showError($('#password_old').parent().find('.errorMsg'));        
        return ;
    }
    if (newpsw =="" )
    {
        showError($('#password_new').parent().find('.errorMsg'));
        return ;
    }
    if (newpsw.length <5)
    {
        
        showError($('#psw2Short'));
        return ;
    }
    if (newpsw != newpsw2 )
    {
        showError($('#password_confirm').parent().find('.errorMsg'));
        return ;
    }
                                                          
    var url =  window.location.href + '/ajaxChangePassword';    
    $.post(url ,{"oldpsw":oldpsw,"newpsw":newpsw },
        function(data){                         
                if(data.status =='ok')
                    alert("ok");
                else
                    alert('ajax error');
          },"json");    
}




function asynGetdataList(id,callback, ajaxUrl)
{                              
    console.log('asynGetdataList:'+ajaxUrl);                                          
    $.post(ajaxUrl,{},function(data){
        if (data.status=='ok')
        {              
              callback(id,data.dataList);
        }
    },"json"); 

}

function onDepartmentArrive(id,departments)
{
   $('#input_'+id).val('');
    $('#ul_'+id +' li').remove();
    var $ul = $('#ul_'+ id);
      $.each(departments,function(idx,value){    
           $ul.append('<li>' + value.data + '</li>');
      });          

   
}                         
function onAjaxReturn_ul(id,datalist)
{
   $('#input_'+id).val('');
    $('#ul_'+id +' li').remove();
    var $ul = $('#ul_'+ id);
      $.each(datalist,function(idx,value){    
           $ul.append('<li>' + value.data + '</li>');
      });             
}
function onAjaxReturn_selOption(id,datalist)
{
    
    $('#'+id +' option').remove();
    var $dom = $('#'+id);
      $.each(datalist,function(idx,value){    
          $dom.append("<option value="+value.id+" >"+value.data+"</option>");
      });          
                                                            
}

function QuickAdd_onClick(obj_id,dialogID)
{
    console.log('QuickAdd_onClick:' + obj_id +',' + dialogID);
  $('.adhocDialog').slideUp("fast");
  if (obj_id=="Department")
  {                                                                                            
    asynGetdataList(obj_id,onAjaxReturn_ul, gbaseUrl + 'AjaxLibs/ajaxGetDepartments');      
  }
  else 
    return false;
                 
    
    var pos = $('#btn_'+obj_id).position();      
                                                                                                                                                              
    // .outerWidth() takes into account border and padding.
    var width = $('#btn_'+obj_id).outerWidth();

    //show the menu directly over the placeholder
    $("#" + dialogID).css({
        position: "absolute",
        top: pos.top + "px",
        left: (pos.left + width+10) + "px"
    }).slideDown("fast");   
}

function closeDialog()
{
    $('.adhocDialog').slideUp("fast");
}

function addNew(obj_id)
{
    console.log('addNew:'+obj_id);
    var count = $('#ul'+obj_id+' li').length+1;
    if (obj_id=="Department")
    {                                                                                      
        var button = '<div id="newDepartment" class="button buttonCross" />';
    }
    else 
        return false;
        
    $('#ul_' + obj_id).append('<li name="new" id=' + count +' style="color:red;">' + $('#input_'+obj_id).val()+'&nbsp;' + button + '</li>');   
}

function QuickAdd_onClick(obj_id,dialogID)
{
    console.log('QuickAdd_onClick:' + obj_id +',' + dialogID);
  $('.adhocDialog').slideUp("fast");
  if (obj_id=="Department")
  {                                                                                     
    asynGetdataList(obj_id,onAjaxReturn_ul,gbaseUrl + 'AjaxLibs/ajaxGetDepartments');      
  }
  else 
    return;
    
    var pos = $('#btn_'+obj_id).position();      
                                                                                                                                                              
    // .outerWidth() takes into account border and padding.
    var width = $('#btn_'+obj_id).outerWidth();

    //show the menu directly over the placeholder
    $("#" + dialogID).css({
        position: "absolute",
        top: pos.top + "px",
        left: (pos.left + width+10) + "px"
    }).slideDown("fast");   
}

function onSaveChange(obj_id)
{
  if (obj_id=="Department")
  {
   saveNewDepartment(obj_id);
  } 
} 


function saveNewDepartment(obj_id)
{
    var newDepts=[];
    
    $('#ul_'+obj_id+' li[name="new"]').each(function(index){
        newDepts.push($.trim($(this).text()));
        console.log('found new item:' + index + '='+$(this).text() + ',name:' + $(this).attr('name'));
    });        
    console.log('saveNewDepartment.gbaseUrl:' + gbaseUrl);
    
    if (newDepts!="")
    {
    
        var url =  gbaseUrl + 'AjaxLibs/ajaxAddNewDepartment';                  
        $.post(url ,{newDepts:newDepts},
            function(data){                         
                    if(data.status =='ok')
                    {
                      $('#ul_'+obj_id+' li[name="new"]').each(function(index){
                        $(this).attr('name',''); //successfully added, remove 'new' flag
                        $(this).css('color','black');
                        $(this).find('.buttonCross').remove();
                      });   
                    }
                    else
                       {
                           $.each(data.errorlist,function(idx,value){
                               console.log('key=>' + value.key);
                               console.log('value=>' + value.error);
                                appendErrorMessage('#ul_'+obj_id,value.key,value.error);                               
                           });
                       }                                    
                       asynGetdataList(obj_id,onAjaxReturn_selOption, gbaseUrl + 'AjaxLibs/ajaxGetDepartments' );      
  
              },"json");        
    }
}

                      
function appendErrorMessage(obj_id,key, errorMsg)
{
    console.log('appendErrorMessage:' + obj_id +','+key);
    $(obj_id+' li[name="new"]').each(function(index){
        console.log(key + (key == $.trim($(this).text()) ? '==' : '!=') + $.trim($(this).text()));
        $(this).attr('name',''); //successfully added, remove 'new' flag
        if (key == $.trim($(this).text()))
        {
            $(this).text($(this).text() + '(' + errorMsg +')');
            console.log('errorMsg:' +errorMsg);                                    
            return false;                      
        }
        else
        {
            $(this).css('color','black');
            $(this).find('.buttonCross').remove();            
        }
        
    });            
}                  